package com.example.yang.iotdevelop9;

import android.app.Activity;
import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import java.math.BigInteger;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 工具类
 * Created by Administrator on 2018/6/27 0027.
 */

public class Tools {
    /**
     * To byte array byte [ ].
     *
     * @param hexString the hex string
     * @return the byte [ ]
     */
    public static byte[] hexString2ByteArray(String hexString) {
        try {
            if (hexString.isEmpty()) return null;
            hexString = hexString.toLowerCase();
            final byte[] byteArray = new byte[hexString.length() >> 1];
            int index = 0;
            for (int i = 0; i < hexString.length(); i++) {
                if (index > hexString.length() - 1)
                    return byteArray;
                byte highDit = (byte) (Character.digit(hexString.charAt(index), 16) & 0xFF);
                byte lowDit = (byte) (Character.digit(hexString.charAt(index + 1), 16) & 0xFF);
                byteArray[i] = (byte) (highDit << 4 | lowDit);
                index += 2;
            }
            return byteArray;
        } catch (Exception e) {
            Log.e("hexString2ByteArray", e.toString());
            return null;
        }
    }

    /**
     * byte[] to Hex string.
     *
     * @param byteArray the byte array
     * @return the string
     */

    public static String byte2HexString(byte[] byteArray) {
        final StringBuilder hexString = new StringBuilder("");
        if (byteArray == null || byteArray.length <= 0)
            return null;
        for (int i = 0; i < byteArray.length; i++) {
            int v = byteArray[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                hexString.append(0);
            }
            hexString.append(hv);
        }
        return hexString.toString().toLowerCase();
    }

    /**
     * 十六进制字符串转十进制
     * @param hexString
     * @return
     */
    public static int hexString2Int(String hexString){
        try {
            return Integer.parseInt(hexString,16);
        } catch (NumberFormatException e) {
            Log.e("hexString2Int","转型错误");
            return Integer.parseInt(null);
        }
    }

    /**
     * byte[]转int
     *
     * @param bytes
     * @return
     */
    public static int byteArrayToInt(byte[] bytes) {
        int value = 0;
        // 由高位到低位
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (bytes[i] & 0x000000FF) << shift;// 往高位游
        }
        return value;
    }

    /**
     * 线程安全 showToast
     */
    public static void showToast(Activity activity, String str) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            // TODO: 2018/7/20 0020  getApplicationContext 防止内存泄漏
            Toast.makeText(activity.getApplicationContext(), str, Toast.LENGTH_SHORT).show();
        } else {
            Looper.prepare();
            Toast.makeText(activity.getApplicationContext(), str, Toast.LENGTH_SHORT).show();
            Looper.loop();
        }
    }

    /**
     * 数组截取
     *
     * @param src
     * @param begin
     * @param count
     * @return
     */
    public static byte[] subBytes(byte[] src, int begin, int count) {
        if (src == null) return null;
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }

    /**
     * 是否使屏幕常亮
     *
     * @param activity
     */
    public static void keepScreenLongLight(Activity activity) {
        Window window = activity.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }


    /*
    判断一个字符串是不是整数
     */
    public static boolean isNumeric(String string) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(string.trim());
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /*
     Android开发中程序判断手机操作系统版本
     */
    public static int getAndroidSDKVersion() {
        int version = 0;
        try {
            version = Integer.valueOf(android.os.Build.VERSION.SDK);
        } catch (NumberFormatException e) {
        }
        return version;
    }

    /*
     * 判断当前系统的语言环境是否为中文
     *
     */
    public static boolean isZh(Context context) {
        Locale locale = context.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh"))
            return true;
        else
            return false;
    }

    /*
    * 判断当前系统的语言环境是否为英文
    *
    */
    public static boolean isEN(Context context) {
        Locale locale = context.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("en"))
            return true;
        else
            return false;
    }

    /**
     * 将16进制 转换成10进制
     *
     * @param str
     * @return
     */
    public static String print10(String str) {

        StringBuffer buff = new StringBuffer();
        String array[] = str.split(" ");
        for (int i = 0; i < array.length; i++) {
            int num = Integer.parseInt(array[i], 16);
            buff.append(String.valueOf((char) num));
        }
        return buff.toString();
    }

    /*
   * 字节数组转字符串
   */
    public static String bytes2String(byte[] b) throws Exception {
        String r = new String(b, "UTF-8");
        return r;
    }

    /*
     * 字符串转字节数组
     */
    public static byte[] string2Bytes(String s) {
        byte[] r = s.getBytes();
        return r;
    }

    /*
     * 字符串转16进制字符串
     */
    public static String string2HexString(String s) throws Exception {
        String r = byte2HexStr(string2Bytes(s));
        return r;
    }

    /**
     * byte转16进制字符串
     *
     * @param b
     * @return
     */
    public static String byte2HexStr(byte[] b) {

        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }

    /**
     * byte转二进制字符串
     *
     * @param bytes
     * @return
     */
    public static String byte2BinStr(byte[] bytes) {
        return new BigInteger(1, bytes).toString(2);// 这里的1代表正数
    }

    /**
     * 将16进制的字符串转换为字节数组
     *
     * @param message * @return 字节数组
     */
    public static byte[] getHexBytes(String message) {
        int len = message.length() / 2;
        char[] chars = message.toCharArray();
        String[] hexStr = new String[len];
        byte[] bytes = new byte[len];
        for (int i = 0, j = 0; j < len; i += 2, j++) {
            hexStr[j] = "" + chars[i] + chars[i + 1];
            bytes[j] = (byte) Integer.parseInt(hexStr[j], 16);
        }
        return bytes;
    }

}
